/// 登录页面
/// 用户登录界面
library;
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:chat_project/providers/auth_provider.dart';
import 'package:chat_project/config/theme_config.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  String? _errorMessage;
  bool _obscurePassword = true;
  bool _isLoading = false;
  
  @override
  void initState() {
    super.initState();
    // 预填充测试账号
    _usernameController.text = 'aaa';
    _passwordController.text = 'aaaaaa';
  }
  
  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }
  
  // 处理登录
  Future<void> _handleLogin() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      try {
        final authProvider = Provider.of<AuthProvider>(context, listen: false);
        final success = await authProvider.login(
          _usernameController.text,
          _passwordController.text,
          forceMock: false, // 使用真实API数据
        );

        if (success && mounted) {
          context.go('/home');
        } else if (mounted) {
          setState(() {
            _errorMessage = '登录失败，请检查您的用户名和密码';
            _isLoading = false;
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            _errorMessage = e.toString();
            _isLoading = false;
          });
        }
      }
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(ThemeConfig.paddingLarge),
            child: Form(
              key: _formKey,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // 图标和标题
                  Center(
                    child: Column(
                      children: [
                        Container(
                          width: 80,
                          height: 80,
                          decoration: BoxDecoration(
                            color: ThemeConfig.primaryColor.withOpacity(0.1),
                            shape: BoxShape.circle,
                          ),
                          child: const Icon(
                            Icons.chat,
                            size: 50,
                            color: ThemeConfig.primaryColor,
                          ),
                        ),
                        const SizedBox(height: 24),
                        const Text(
                          '欢迎回来',
                          style: TextStyle(
                            fontSize: ThemeConfig.fontSizeXXLarge,
                            fontWeight: FontWeight.bold,
                            color: ThemeConfig.textPrimaryColor,
                          ),
                        ),
                        const SizedBox(height: 8),
                        const Text(
                          '请登录您的账号',
                          style: TextStyle(
                            fontSize: ThemeConfig.fontSizeRegular,
                            color: ThemeConfig.textSecondaryColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 48),
                  
                  // 错误消息
                  if (_errorMessage != null) ...[
                    Container(
                      padding: const EdgeInsets.all(ThemeConfig.paddingRegular),
                      decoration: BoxDecoration(
                        color: ThemeConfig.errorColor.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusRegular),
                      ),
                      child: Text(
                        _errorMessage!,
                        style: const TextStyle(
                          color: ThemeConfig.errorColor,
                          fontSize: ThemeConfig.fontSizeRegular,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                    const SizedBox(height: 24),
                  ],
                  
                  // 用户名/邮箱输入
                  TextFormField(
                    controller: _usernameController,
                    decoration: InputDecoration(
                      labelText: '用户名或邮箱',
                      prefixIcon: const Icon(Icons.person),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusRegular),
                      ),
                    ),
                    keyboardType: TextInputType.emailAddress,
                    textInputAction: TextInputAction.next,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入用户名或邮箱';
                      }
                      return null;
                    },
                    enabled: !_isLoading,
                  ),
                  const SizedBox(height: 16),
                  
                  // 密码输入
                  TextFormField(
                    controller: _passwordController,
                    decoration: InputDecoration(
                      labelText: '密码',
                      prefixIcon: const Icon(Icons.lock),
                      suffixIcon: IconButton(
                        icon: Icon(_obscurePassword ? Icons.visibility : Icons.visibility_off),
                        onPressed: () {
                          setState(() {
                            _obscurePassword = !_obscurePassword;
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusRegular),
                      ),
                    ),
                    obscureText: _obscurePassword,
                    textInputAction: TextInputAction.done,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入密码';
                      }
                      if (value.length < 6) {
                        return '密码至少需要6个字符';
                      }
                      return null;
                    },
                    enabled: !_isLoading,
                    onFieldSubmitted: (_) => _handleLogin(),
                  ),
                  const SizedBox(height: 24),
                  
                  // 登录按钮
                  ElevatedButton(
                    onPressed: _isLoading ? null : _handleLogin,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ThemeConfig.primaryColor,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusRegular),
                      ),
                    ),
                    child: _isLoading
                        ? LoadingAnimationWidget.threeArchedCircle(
                            color: Colors.white,
                            size: 24,
                          )
                        : const Text(
                            '登录',
                            style: TextStyle(
                              fontSize: ThemeConfig.fontSizeMedium,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                  ),
                  const SizedBox(height: 24),
                  
                  // 注册链接
                  Center(
                    child: TextButton(
                      onPressed: _isLoading ? null : () => context.go('/register'),
                      child: RichText(
                        text: const TextSpan(
                          style: TextStyle(
                            fontSize: ThemeConfig.fontSizeRegular,
                            color: ThemeConfig.textPrimaryColor,
                          ),
                          children: [
                            TextSpan(text: '还没有账号？'),
                            TextSpan(
                              text: '立即注册',
                              style: TextStyle(
                                color: ThemeConfig.primaryColor,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
} 